#!/usr/bin/env python
# -*- coding: utf8 -*-
# $Id :  $



# Copyright 2008-2010, Pascal Fautrero & JCharles
#
# This file is part of PyArchiver.
# 
# PyArchiver is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyArchiver is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyArchiver.  If not, see <http://www.gnu.org/licenses/>./>.



############################################################################
# About     :  PyArchiver was built using Python 2.7,                      #
#              wxPython 2.8.11.0 unicode, and wxWidgets                    #
# Platform  :  Tested on Windows XP or Seven, Linux Ubuntu and Mac OSX     #
# Comment   :  To test the MySQL database, please install WampServer       #
#              --------->    WampServer is a local server    <--------     #
#              ---------->    http://www.wampserver.com    <----------     #
#              (available for Windows, linux and MacOSX (multilanguage)    #
############################################################################


# Import packages
    
try:
    import wx                    # This module uses the new wx namespace
except ImportError:
    raise ImportError, "The wxPython module is required to run this program."

import sys
import os
import platform
import locale

import images
import SplashScreen
import VersionInfos

import MenuBar
import StatusBar
import TaskBarIcon

from   wx.lib.buttons            import GenBitmapTextButton
import ListCtrlVirtual
import SearchCtrl

import WarningDialog
import SaveDialog
import PasswordDialog
import SettingDialog

import MementoProvider
import AboutNotebook

import ClassMySQL    

import PrintFramework
import ScrolledWindow
import ConfigParser              # Used to exploit .ini files
import hashlib

getTextType = "wx"               # Using wxPython's GetTranslation

_ = wx.GetTranslation            # Define _ or add _ to builtins in your app file

#---------------------------------------------------------------------------

class My_Frame(wx.Frame):
    def __init__(self, parent, id, title):        

        #-------------------------------------------------------------------
        
        self.cfg = wx.Config("size")
        if self.cfg.Exists("Width"):
            w, h = self.cfg.ReadInt("Width"), self.cfg.ReadInt("Height")
        else:
            (w, h) = (940, 669)

        #-------------------------------------------------------------------
            
        wx.Frame.__init__(self, parent, -1, title,
                          wx.DefaultPosition, wx.Size(w, h),
                          style=wx.DEFAULT_FRAME_STYLE |
                          wx.NO_FULL_REPAINT_ON_RESIZE)
        
        # Bind some events to an events handler
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
        self.Bind(wx.EVT_ICONIZE, self.OnIconfiy)
        self.Bind(wx.EVT_MAXIMIZE, self.OnMaximize)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)

        #-------------------------------------------------------------------

        # Global variables       
        self.shell = None
        self.isRolled = False
        self.isMemento = False
        self.isAbout = False
        
        #-------------------------------------------------------------------

        # A panel is needed for tab-traversal and platform-independent
        # background color capabilities.        
        self.panel = wx.Panel(self, id=-1, style=wx.TAB_TRAVERSAL)
        
        # Bind the enter window events to an events handler
        self.panel.Bind(wx.EVT_ENTER_WINDOW, self.OnPanelInfo, id=-1)

        #-------------------------------------------------------------------
        
        # Simplified init method
        self.loadDatabase()
        self.createMenuBar()
        self.createStatusBar()
        self.createTaskBarIcon()
        self.createStaticText()
        self.createListCtrl()
        self.populateListCtrl()
        self.createSearchCtrl()
        self.createPrintData()
        self.createBtnBar()
        self.createImage()
        self.doLayout()
        
        #-------------------------------------------------------------------
        
        self.CenterOnScreen()

    #-----------------------------------------------------------------------

    def loadDatabase(self):
        self.dbObject = ClassMySQL.DataBaseObject("basearchiver", "tablearchiver")

    #-----------------------------------------------------------------------
        
    def createMenuBar(self):
        self.menu = MenuBar.My_MenuBar(self)
        self.SetMenuBar(self.menu)
        
        # Bind some menus events to an events handler
        self.Bind(wx.EVT_MENU, self.OnSave, id=500)
        self.Bind(wx.EVT_MENU, self.OnPrint, id=501)
        self.Bind(wx.EVT_MENU, self.OnClose, id=502)

        self.Bind(wx.EVT_MENU, self.OnDelete, id=503)
        self.Bind(wx.EVT_MENU, self.OnSetting, id=504)

        self.Bind(wx.EVT_MENU, self.OnRoll, id=505)
        self.Bind(wx.EVT_MENU, self.OnUnRoll, id=506)
        self.Bind(wx.EVT_MENU, self.OnShellWindow, id=507)
        self.Bind(wx.EVT_MENU, self.OnWidgetInspector, id=508)
        
        self.Bind(wx.EVT_MENU, self.OnMemento, id=509)
        self.Bind(wx.EVT_MENU, self.OnAbout, id=510)
        
    #-----------------------------------------------------------------------
        
    def createStatusBar(self):
        self.sb = StatusBar.My_CustomStatusBar(self)
        self.SetStatusBar(self.sb)
        
    #-----------------------------------------------------------------------
        
    def createTaskBarIcon(self):
        self.tskic = TaskBarIcon.My_TaskBarIcon(self)
                
    #-----------------------------------------------------------------------
        
    def createStaticText(self):
        # Create some StaticText
        self.text1 = wx.StaticText(self.panel, id=-1, label=_("Manual selection :"))
        font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        font.SetWeight(wx.BOLD)
        self.text1.SetFont(font)
        self.text1.SetForegroundColour("#646464")
        
        # === Warning : self.text2 and text3 are used in ListCtrlVirtual.py
        self.panel1 = wx.Panel(self.panel, id=-1, style=wx.BORDER_SIMPLE)
        self.panel1.SetBackgroundColour("#fefed9")		
        self.text2 = wx.StaticText(self.panel1, id=-1, label="",
                                   style=wx.ALIGN_RIGHT | wx.ST_NO_AUTORESIZE)
        self.text2.SetForegroundColour("#68b1d8")
        
        # === Warning : self.text2 and text3 are used in ListCtrlVirtual.py
        self.panel2 = wx.Panel(self.panel, id=-1, style=wx.BORDER_SIMPLE)
        self.panel2.SetBackgroundColour("#fefed9")	
        self.text3 = wx.StaticText(self.panel2, id=-1, label="",
                                   style=wx.ALIGN_RIGHT | wx.ST_NO_AUTORESIZE)
        self.text3.SetForegroundColour("#68b1d8")
        
        self.text4 = wx.StaticText(self.panel, id=-1, label=_("Automatic search :"))
        font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        font.SetWeight(wx.BOLD)
        self.text4.SetFont(font)
        self.text4.SetForegroundColour("#646464")
        
        self.text5 = wx.StaticText(self.panel, id=-1, label=_("Input :  "))
        
    #-----------------------------------------------------------------------

    def createListCtrl(self):
        # Create a BitmapTextButton for ListCtrlFolders
        bmp = images.Btn_Folders.GetBitmap()
        self.btnFolders = GenBitmapTextButton(self.panel, id=-1,
                                              size=(200, -1),
                                              bitmap=bmp,
                                              label=_(" Sources List "))
        font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        font.SetWeight(wx.BOLD)
        self.btnFolders.SetFont(font)        
        self.btnFolders.SetBezelWidth(2)
        
        self.btnFolders.SetBackgroundColour("#4f4f4f")
        self.btnFolders.SetForegroundColour(wx.WHITE)
        
        # Bind some events to an events handler
        self.Bind(wx.EVT_BUTTON, self.OnFolders, self.btnFolders)
        self.btnFolders.Bind(wx.EVT_ENTER_WINDOW, self.OnBtnEnter)
        self.btnFolders.Bind(wx.EVT_ENTER_WINDOW, self.OnFoldersInfo, id=-1)
        self.btnFolders.Bind(wx.EVT_LEAVE_WINDOW, self.OnBtnLeave)
        
        #----------
        
        # if wx.Platform == "__WXMAC__":
        #     wx.SystemOptions.SetOptionInt("mac.listctrl.always_use_generic", 0)
        
        self.listFolders = ListCtrlVirtual.My_ListCtrlFolders(self.panel, self)
        
        #-------------------------------------------------------------------
        
        # Create a BitmapTextButton for ListCtrlSupports
        bmp = images.Btn_Supports.GetBitmap()
        self.btnSupports = GenBitmapTextButton(self.panel, id=-1,
                                               size=(200, -1),
                                               bitmap=bmp,
                                               label=_(" Supports List "))
        font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        font.SetWeight(wx.BOLD)
        self.btnSupports.SetFont(font)        
        self.btnSupports.SetBezelWidth(2)
        
        self.btnSupports.SetBackgroundColour("#4f4f4f")
        self.btnSupports.SetForegroundColour(wx.WHITE)
        
        # Bind some events to an events handler
        self.Bind(wx.EVT_BUTTON, self.OnSupports, self.btnSupports)
        self.btnSupports.Bind(wx.EVT_ENTER_WINDOW, self.OnBtnEnter)
        self.btnSupports.Bind(wx.EVT_ENTER_WINDOW, self.OnSupportsInfo, id=-1)
        self.btnSupports.Bind(wx.EVT_LEAVE_WINDOW, self.OnBtnLeave)
        
        #----------
        
        # if wx.Platform == "__WXMAC__":
        #     wx.SystemOptions.SetOptionInt("mac.listctrl.always_use_generic", 0)
        
        self.listSupports = ListCtrlVirtual.My_ListCtrlSupports(self.panel, self)

    #-----------------------------------------------------------------------

    def populateListCtrl(self):
        self.SelectedSupport = ""
        if self.dbObject:
            self.listFolders.SetMyRows(self.dbObject.RetrieveRecords("Dossiers"))   ######
            self.listFolders.SpecialRefresh()            
            self.listSupports.SetMyRows(self.dbObject.RetrieveRecords("Supports"))   ######
            self.listSupports.SpecialRefresh()  		

    #-----------------------------------------------------------------------
        
    def createSearchCtrl(self):
        self.searchCtrl = SearchCtrl.My_SearchCtrl(self.panel, self)
       
        # Bind an enter window events to an events handler
        self.searchCtrl.Bind(wx.EVT_ENTER_WINDOW, self.OnSearchInfo, id=-1)
        self.Bind(wx.EVT_SIZE, self.OnResize)
       
    #-----------------------------------------------------------------------

    def createPrintData(self):
        self.printData = wx.PrintData()
        self.printData.SetPaperId(wx.PAPER_A4)
        self.printData.SetPrintMode(wx.PRINT_MODE_PRINTER)
        self.printData.SetOrientation(wx.PORTRAIT)
        self.printData.SetQuality(wx.PRINT_QUALITY_HIGH)
        self.printData.SetColour(False)
        # self.printData.SetPrinterName("")    # Printer Name 
        # self.printData.SetNoCopies(30)       # Copies Number 
        # self.printData.SetCollate(True)      # Combined Files 
            
        self.canvas = ScrolledWindow.My_Canvas(self.panel, size=(0, 0))

    #-----------------------------------------------------------------------
        
    def createBtnBar(self):
        self.btnSave = wx.Button(self.panel, id=wx.ID_SAVE, label="", size=(90, -1))
        self.btnPrint = wx.Button(self.panel, id=wx.ID_PRINT, label="", size=(90, -1))
        self.btnDelete = wx.Button(self.panel, id=wx.ID_DELETE, label="", size=(90, -1))
        self.btnAbout = wx.Button(self.panel, id=wx.ID_ABOUT, label="", size=(90, -1))
        self.btnQuit = wx.Button(self.panel, id=wx.ID_EXIT, label="", size=(90, -1))
        
        # Bind some buttons events to an events handler
        self.Bind(wx.EVT_BUTTON, self.OnSave, self.btnSave)
        self.Bind(wx.EVT_BUTTON, self.OnPrint, self.btnPrint)
        self.Bind(wx.EVT_BUTTON, self.OnDelete, self.btnDelete)
        self.Bind(wx.EVT_BUTTON, self.OnAbout, self.btnAbout)
        self.Bind(wx.EVT_BUTTON, self.OnClose, self.btnQuit)
        
        # Bind some enter window events to an events handler
        self.btnSave.Bind(wx.EVT_ENTER_WINDOW, self.OnSaveInfo, id=wx.ID_SAVE)
        self.btnPrint.Bind(wx.EVT_ENTER_WINDOW, self.OnPrintInfo, id=wx.ID_PRINT)
        self.btnDelete.Bind(wx.EVT_ENTER_WINDOW, self.OnDeleteInfo, id=wx.ID_DELETE)
        self.btnAbout.Bind(wx.EVT_ENTER_WINDOW, self.OnAboutInfo, id=wx.ID_ABOUT)
        self.btnQuit.Bind(wx.EVT_ENTER_WINDOW, self.OnCloseInfo, id=wx.ID_EXIT)
        
        # Bind the events size to an events handler
        self.Bind(wx.EVT_SIZE, self.OnResize)
        
    #-----------------------------------------------------------------------
        
    def createImage(self):
        bmp = images.Icons.GetBitmap()
        self.img = wx.StaticBitmap(self.panel, -1)
        self.img.SetBitmap(bmp)
        self.img.SetToolTipString(_("Cool !"))
        
        # Bind the size events to an events handler
        self.Bind(wx.EVT_SIZE, self.OnResize)
        
    #-----------------------------------------------------------------------
        
    def doLayout(self):
        txt1Sizer = wx.BoxSizer(wx.HORIZONTAL)
        
        btnFoldersSizer = wx.BoxSizer(wx.HORIZONTAL)
        listFoldersSizer = wx.BoxSizer(wx.VERTICAL)
        txt2Sizer = wx.BoxSizer(wx.HORIZONTAL)
        vbox2 = wx.BoxSizer(wx.VERTICAL)
        
        btnSupportsSizer = wx.BoxSizer(wx.HORIZONTAL)
        listSupportsSizer = wx.BoxSizer(wx.VERTICAL)
        txt3Sizer = wx.BoxSizer(wx.HORIZONTAL)
        vbox3 = wx.BoxSizer(wx.VERTICAL)
        
        txt4Sizer = wx.BoxSizer(wx.HORIZONTAL)
        txtCtrlSizer = wx.BoxSizer(wx.HORIZONTAL)
        btnSizer = wx.BoxSizer(wx.VERTICAL)
        
        btnQuitSizer = wx.BoxSizer(wx.HORIZONTAL)
        
        #--------------

        # wx.BoxSizer(window, proportion, flag, border)        
        # wx.BoxSizer(sizer, proportion, flag, border)        
        txt1Sizer.Add(self.text1, 1, wx.EXPAND, 0)
        
        btnFoldersSizer.Add(self.btnFolders, 1, wx.EXPAND | wx.BOTTOM, 2)
        txt2Sizer.Add(self.text2, 1, wx.ALIGN_RIGHT | wx.EXPAND | wx.ALL, 2)
        vbox2.Add(txt2Sizer, 1, wx.ALIGN_CENTRE | wx.EXPAND | wx.ALL, 2)
        
        listFoldersSizer.Add(btnFoldersSizer, 0, wx.EXPAND, 0)
        listFoldersSizer.Add(self.listFolders, 1, wx.EXPAND, 0)
        listFoldersSizer.Add(self.panel1, 0, wx.ALL | wx.EXPAND, 0)

        btnSupportsSizer.Add(self.btnSupports, 1, wx.EXPAND | wx.BOTTOM, 2)
        txt3Sizer.Add(self.text3, 1, wx.ALIGN_RIGHT | wx.EXPAND | wx.ALL, 2)
        vbox3.Add(txt3Sizer, 1, wx.ALIGN_CENTRE | wx.EXPAND | wx.ALL, 2)
        
        listSupportsSizer.Add(btnSupportsSizer, 0, wx.EXPAND, 0)
        listSupportsSizer.Add(self.listSupports, 1, wx.EXPAND, 0)
        listSupportsSizer.Add(self.panel2, 0, wx.ALL | wx.EXPAND, 0)
        
        txt4Sizer.Add(self.text4, 0, wx.EXPAND, 0)
        txtCtrlSizer.Add(self.text5, 1, wx.EXPAND | wx.LEFT, 20)
        txtCtrlSizer.Add(self.searchCtrl, 0, wx.EXPAND, 0)
        
        btnSizer.Add(self.img, 0, wx.LEFT | wx.BOTTOM |
                     wx.ALIGN_CENTER_HORIZONTAL, 10)
        btnSizer.Add(self.btnSave, 0, wx.LEFT | wx.BOTTOM |
                     wx.ALIGN_CENTER_HORIZONTAL, 10)
        btnSizer.Add(self.btnPrint, 0, wx.LEFT | wx.BOTTOM |
                     wx.ALIGN_CENTER_HORIZONTAL, 10)
        btnSizer.Add(self.btnDelete, 0, wx.LEFT | wx.BOTTOM |
                     wx.ALIGN_CENTER_HORIZONTAL, 10)
        btnSizer.Add(self.btnAbout, 0, wx.LEFT | wx.BOTTOM |
                     wx.ALIGN_CENTER_HORIZONTAL, 10)
        
        btnQuitSizer.Add(self.btnQuit, 0, wx.EXPAND, 0)
        
        #--------------
        #--------------
        
        topSizer = wx.BoxSizer(wx.HORIZONTAL)
        
        #--------------
        
        topSizer.Add(listFoldersSizer, 1, wx.EXPAND | wx.RIGHT, 6)
        topSizer.Add(listSupportsSizer, 1, wx.EXPAND | wx.LEFT, 6)
        topSizer.Add(btnSizer, 0, wx.EXPAND, 0)
        
        #--------------
        #--------------
        
        allSizer = wx.BoxSizer(wx.VERTICAL)
        
        #--------------
        
        allSizer.Add(txt1Sizer, 0, wx.EXPAND | wx.BOTTOM, 10)
        allSizer.Add(topSizer, 1, wx.EXPAND, 0)

        allSizer.Add(txt4Sizer, 0, wx.EXPAND | wx.LEFT | wx.TOP, 13)

        allSizer.Add(txtCtrlSizer, 0, wx.LEFT | wx.TOP, 13)
        allSizer.Add(btnQuitSizer, 0, wx.ALIGN_RIGHT)
        
        #--------------
        #--------------
        
        borderSizer = wx.BoxSizer(wx.VERTICAL)
        
        #--------------
        
        borderSizer.Add(allSizer, 1, wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL , 13)
        
        #--------------
        #--------------

        self.panel1.SetAutoLayout(True)
        self.panel1.SetSizer(vbox2)

        self.panel2.SetAutoLayout(True)
        self.panel2.SetSizer(vbox3)

        self.panel.SetAutoLayout(True)
        self.panel.SetSizer(borderSizer)
        borderSizer.Fit(self.panel)
        
    #-----------------------------------------------------------------------

    # StatusBar help        
    def OnPanelInfo(self, event):
        self.sb.SetStatusText(text=_("Welcome to PyArchiver !"))
        event.Skip()
        
    def OnFoldersInfo(self, event):
        self.sb.SetStatusText(text=_("Displays all sources of the database."))
        event.Skip()
        
    def OnSupportsInfo(self, event):
        self.sb.SetStatusText(text=_("Displays all supports of the database."))
        event.Skip()
        
    def OnSaveInfo(self, event):
        self.sb.SetStatusText(text=_("Save source in the database."))
        event.Skip()
        
    def OnPrintInfo(self, event):
        self.sb.SetStatusText(text=_("Print the content of support selected."))
        event.Skip()
        
    def OnDeleteInfo(self, event):
        self.sb.SetStatusText(text=_("Removes source or support of the database."))
        event.Skip()
        
    def OnAboutInfo(self, event):
        self.sb.SetStatusText(text=_("About this application."))
        event.Skip()
        
    def OnCloseInfo(self, event):
        self.sb.SetStatusText(text=_("Quit this application."))
        event.Skip()
        
    def OnSearchInfo(self, event):
        self.sb.SetStatusText(text=_("Search source of the data base (validate with the Enter key)."))
        event.Skip()
        
    #-----------------------------------------------------------------------

    def OnBtnEnter(self, event):
        self.obj = event.GetEventObject()
        self.obj.SetBackgroundColour("GRAY")
        self.obj.Refresh()
        
    def OnBtnLeave(self, event):
        self.obj = event.GetEventObject()
        self.obj.SetBackgroundColour("#4f4f4f")
        self.obj.Refresh()
        
    #-----------------------------------------------------------------------
        
    def OnRoll(self, event):
        if self.isRolled == True:
            return
        self.isRolled = True

        self.size = self.GetSize()
            
        if wx.Platform == "__WXMSW__":
            self.SetSize((-1, 0))
            self.SetPosition((-1, -1)) 

        else:
            self.SetClientSize((-1, 0))
            self.SetPosition((-1, -1))          

        self.GetTitle()
        self.SetTitle(_("PyArchiver v%s - F4 key for UnRoll")
                      % VersionInfos.APPLICATIONVERSION_STRING)

        
    def OnUnRoll(self, event):
        self.isRolled = False

        self.SetSize(self.size)
        self.SetPosition((-1, -1))

        self.GetTitle()
        self.SetTitle(_("PyArchiver v%s")
                      % VersionInfos.APPLICATIONVERSION_STRING)
        
    #----------------------------------------------------------------------
        
    def OnSwitchlangFr(self):
        wx.GetApp().SetLang("fr")


    def OnSwitchlangEn(self):
        wx.GetApp().SetLang("en")
        
    #-----------------------------------------------------------------------

    def VerifyPassword (self, password):
        """ Check the input password """

        hashHardcoded = "f4353bd17732e54b6b120e628b211e78c279e330"
        hash = hashlib.sha1()
        hash.update(password)
        if hash.hexdigest() == hashHardcoded:
            result = True
        else:
            result = False	
        return result		

    #-----------------------------------------------------------------------
    
    def FilterSupports(self, item_text):
        self.listSupports.SetMyRows(self.dbObject.FilterField("dossiers", item_text, "supports"))
        self.listSupports.SpecialRefresh()  
        self.SelectedSupport = ""
        self.SelectedFolder = ""		

    #-----------------------------------------------------------------------
        
    def FilterFolders(self, item_text):
        self.listFolders.SetMyRows(self.dbObject.FilterField("supports", item_text, "dossiers"))
        self.listFolders.SpecialRefresh() 
        self.SelectedSupport = ""
        self.SelectedFolder = "" 		

    #-----------------------------------------------------------------------
            
    def OpenDrive (self, drivename):
        """ Lister tous les dossiers localises sur le lecteur de cdrom """
        
        try:
            print drivename
            FileList = os.listdir(drivename)
            return FileList
        except os.error:
            onerror(os.listdir, path, sys.exc_info())
            print _("The drive %s is inaccessible.") % drivename
            return False

    #-----------------------------------------------------------------------

    def RetrieveDrivePath(self):
        """ Retrouver l'emplacement du lecteur de cdrom """
        
        config = ConfigParser.ConfigParser()
        config.read("PyArchiver.ini")	
        return config.get("Drives", "drive1")
            
    #-----------------------------------------------------------------------
        
    def OnSave(self, event):
        """ Enregistrer un support dans la base de donnees """

        if self.dbObject == None:
            return False

        self.saveDlg = WarningDialog.My_WarningDialog(self,
                                                      message=_("Make sure you have \ninserted a CD/DVD in the drive \nbefore start saving !"),
                                                      title=_("Warning"),
                                                      pos=(-1, -1))
        
        self.saveDialog = SaveDialog.My_SaveDialog(self,
                                                   title=_("Save a support"),
                                                   pos=(-1, -1))

        result = False
        if self.saveDialog.PressedButton() == True:
            ContentOfDrive = self.OpenDrive(self.RetrieveDrivePath())
            ThisSupport = self.saveDialog.GetValue()
            if ThisSupport != "":
                if ContentOfDrive:
                    self.dbObject.FillDataBase(self.RetrieveDrivePath(), ContentOfDrive, ThisSupport)
                self.listFolders.SetMyRows(self.dbObject.RetrieveRecords("dossiers"))
                self.listFolders.SpecialRefresh()            
                self.listSupports.SetMyRows(self.dbObject.RetrieveRecords("supports"))
                self.listSupports.SpecialRefresh() 
                result = True
            else:
                print "Support must have a name !"
        self.saveDialog.Destroy()
        return result

    #----------------------------------------------------------------------
        
    def OnPrint(self, event):
        """ Visualiser et imprimer une jaquette """

        self.printDlg = WarningDialog.My_WarningDialog(self,
                                                       message=_("Make sure you have \nselected a Support before \nto launch the printing !"),
                                                       title=_("Warning"),
                                                       pos=(-1, -1))
            
        if wx.Platform == "__WXGTK__":
            self.pdd = wx.PrintDialogData(self.printData)
            self.pdd.SetPrintToFile(True)      # Printed to file 
            # self.pdd.SetPrintData(self.printData)
            # self.pdd.SetMinPage(2)
            # self.pdd.SetMaxPage(20)
            # self.pdd.SetFromPage(1)          # Pages series (from x - to y)
            # self.pdd.SetToPage(2)

            printer = wx.Printer(self.pdd)
            printout = PrintFramework.My_Printout(self.canvas, _("  - Jacket"))
            printer.Print(self, printout, True)

            
        else:
            self.pdd = wx.PrintDialogData(self.printData)
            # self.pdd.SetPrintData(self.printData)
            # self.pdd.SetMinPage(2)
            # self.pdd.SetMaxPage(20)
            # self.pdd.SetFromPage(1)          # Pages series (from x - to y)
            # self.pdd.SetToPage(2)
            # self.pdd.SetPrintToFile(True)    # Printed to file 
            
            printout = PrintFramework.My_Printout(self.canvas, _("  - Jacket"))
            printout2 = PrintFramework.My_Printout(self.canvas, _("  - Jacket"))
            self.preview = wx.PrintPreview(printout, printout2, self.pdd)

            if not self.preview.Ok():
                wx.MessageBox(_("There was a problem printing.\nPerhaps your current printer is \nnot set correctly ?"),
                              _("Printing"), wx.OK)
                return
        
            # Initial zoom value
            if wx.Platform == "__WXMAC__":
                self.preview.SetZoom(55)
            else:
                self.preview.SetZoom(40) 
        
            pfrm = wx.PreviewFrame(self.preview, None,
                                   _("Preview"))

            frameicon = images.Printing.GetIcon()
            pfrm.SetIcon(frameicon)
        
            pfrm.Initialize()
        
            pfrm.SetPosition(self.GetPosition())
            pfrm.SetSize(self.GetSize())
            # pfrm.Maximize()
            pfrm.Show(True)
           
    #----------------------------------------------------------------------
        
    def OnDelete(self, event):
        """ Supprimer un support de la base de donnees """

        self.deleteDlg = WarningDialog.My_WarningDialog(self,
                                                        message=_("Make sure you have \ninserted a Support before \nactivate the deleting !"),
                                                        title=_("Warning"),
                                                        pos=(-1, -1))
        
        self.pwdDialog = PasswordDialog.My_PasswordDialog(self,
                                                          title=_("Delete an entry"),
                                                          pos=(-1, -1))

        if self.VerifyPassword(self.pwdDialog.getpassword()):
            if  self.SelectedSupport != "":
                print self.SelectedSupport
                self.dbObject.DeleteSupport(self.SelectedSupport)
                self.listFolders.SetMyRows(self.dbObject.RetrieveRecords("dossiers"))
                self.listSupports.SetMyRows(self.dbObject.RetrieveRecords("supports"))
                self.listSupports.SpecialRefresh()
                self.listFolders.SpecialRefresh()
                self.SelectedSupport = ""

            elif self.SelectedFolder != "":
                print self.SelectedFolder
                self.dbObject.DeleteFolder(self.SelectedFolder)
                self.listFolders.SetMyRows(self.dbObject.RetrieveRecords("dossiers"))
                self.listSupports.SetMyRows(self.dbObject.RetrieveRecords("supports"))
                self.listSupports.SpecialRefresh()
                self.listFolders.SpecialRefresh()
                self.SelectedFolder = ""
        
    #-----------------------------------------------------------------------
        
    def OnAbout(self, event):
        self.about = AboutNotebook.My_AboutNotebook(self)
        
    #-----------------------------------------------------------------------
        
    def OnMemento(self, event):
        self.memento = MementoProvider.My_Memento(self)

    #-----------------------------------------------------------------------
        
    def OnSetting(self, event):
        self.setting = SettingDialog.My_SettingDialog(self)

    #-----------------------------------------------------------------------
    def OnShellWindow(self, event):
        if self.shell:
            # If it already exists then just make sure it's visible
            s = self.shell
            if s.IsIconized():
                s.Iconize(False)
            s.Raise()
        else:
            # Make a PyShell window
            from wx import py
            namespace = { 'wx'    : wx,
                          'app'   : wx.GetApp(),
                          'frame' : self,
                          }
            self.shell = py.shell.ShellFrame(None, locals=namespace)
            self.shell.SetSize((640,480))
            self.shell.Show()

            # Hook the close event of the main frame window so that we
            # close the shell at the same time if it still exists            
            def CloseShell(event):
                if self.shell:
                    self.shell.Close()
                event.Skip()
            self.Bind(wx.EVT_CLOSE, CloseShell)

    #-----------------------------------------------------------------------
            
    def OnWidgetInspector(self, event):
        # Activate the widget inspection tool
        from wx.lib.inspection import InspectionTool
        if not InspectionTool().initialized:
            InspectionTool().Init()

        # Find a widget to be selected in the tree.  Use either the
        # one under the cursor, if any, or this frame.
        wnd = wx.FindWindowAtPointer()
        if not wnd:
            wnd = self
        InspectionTool().Show(wnd, True)
        
    #-----------------------------------------------------------------------
        
    def OnResize(self, event):
        self.img.Refresh(), self.panel1.Refresh(),
        self.panel2.Refresh(), self.searchCtrl.Refresh()
        event.Skip()

    #-----------------------------------------------------------------------
    
    def OnFolders(self, event):
        """ Lister tous les dossiers de la base """        

        if self.dbObject:
            self.listFolders.SetMyRows(self.dbObject.RetrieveRecords("dossiers"))
            self.listFolders.SpecialRefresh()            
 
    #----------------------------------------------------------------------

    def OnSupports(self, event):
        """ Lister tous les supports de la base """        

        if self.dbObject:
            self.listSupports.SetMyRows(self.dbObject.RetrieveRecords("supports"))
            self.listSupports.SpecialRefresh()
            
    #-----------------------------------------------------------------------

    def OnEraseBackground(self, event):
        dc = event.GetDC()
        if not dc:
            dc = wx.ClientDC(self)
            rect = self.GetUpdateRegion().GetBox()
            dc.SetClippingRect(rect)

    #-----------------------------------------------------------------------
            
    def OnIconfiy(self, event):
        event.Skip()

    #-----------------------------------------------------------------------
        
    def OnMaximize(self, event):
        event.Skip()

    #-----------------------------------------------------------------------
        
    def OnClose(self, event):
        self.Close(True)
        
    #-----------------------------------------------------------------------
        
    def OnCloseWindow(self, event):
        """ Quit this application """

        dlg = wx.MessageDialog(self,
                               message=_("\nDo you really quit this application ?"),
                               caption=_("Quit"),
                               style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)

        if dlg.ShowModal() == wx.ID_YES:
            if self.tskic is not None:
                self.tskic.Destroy()

            self.sb.timer.Stop()
            del self.sb.timer
            event.Skip()
            self.Destroy()
        else:
            dlg.Destroy()
        
#---------------------------------------------------------------------------
           
class My_App(wx.App):
    def OnInit(self):
        wx.InitAllImageHandlers()
        
        # Simplified init method 
        self.InitI18n()   # Internationalization (i18n)
        self.DoConfig()   # Language configuration

        self.SetLang(self.config.Read("Language"))
    
        # Check runtime version
        if VersionInfos.WXPYTHONVERSION_STRING != wx.VERSION_STRING:
            wx.MessageBox(caption=_("Warning"),
                          message=_("You're using version %s of wxPython, but this \napp was written for version %s.\nThere may be some version incompatibilities...")
                          % (wx.VERSION_STRING, VersionInfos.WXPYTHONVERSION_STRING))

        # Create and show the splash screen.  It will then create 
        # and show the main frame when it is time to do so
        wx.SystemOptions.SetOptionInt("mac.window-plain-transition", 1)
        self.SetAppName(_("PyArchiver"))
        
        bmp = images.SplashScreen.GetBitmap()
        self.splash = SplashScreen.My_SplashScreenCustom(None, bitmap=bmp)
        self.splash.Show()
        #self.SetTopWindow(self.splash)
        return True
        
    #-----------------------------------------------------------------------

    def InitI18n(self):
        # Set locale for wxWidgets
        # usually you would define wx.Locale in your wx.App.OnInit class.
        # for the demo we just define it in this module
        self.locale = None
        # wx.Locale.AddCatalogLookupPathPrefix(opj('data/locale'))
        wx.Locale.AddCatalogLookupPathPrefix("locale")
        self.updateLanguage(wx.LANGUAGE_DEFAULT)


    def updateLanguage(self, lang):
        # Make *sure* any existing locale is deleted before the new
        # one is created.  The old C++ object needs to be deleted
        # before the new one is created, and if we just assign a new
        # instance to the old Python variable, the old C++ locale will
        # not be destroyed soon enough, likely causing a crash.
        if self.locale:
            assert sys.getrefcount(self.locale) <= 2
            del self.locale
        
        # create a locale object for this language
        self.locale = wx.Locale(lang)
        if self.locale.IsOk():
            self.locale.AddCatalog("myapp")
        else:
            self.locale = None
            
    #-----------------------------------------------------------------------
        
    def DoConfig(self):
        """
        Do configuration stuff here (either registery or file)
        ApplicationName: application name
        VendorName: author or company
        Language: en (default)
        Keys: (e.g.)
        ProgramLocation: cwd
        ConfigLocation: path\Config\Config.cfg
        ApplicationVersion : application version
        
        """

        appVersion = "%s" % VersionInfos.APPLICATIONVERSION_STRING
        progLoc = os.getcwd()
        configLoc = os.path.join(progLoc, "Config\Config.cfg")
        
        self.config = wx.FileConfig(appName="PyArchiver",
                                    vendorName="Pascal Fautrero and JCharles",
                                    localFilename=configLoc,
                                    style=wx.CONFIG_USE_LOCAL_FILE)

        if not self.config.HasEntry("ProgramLocation"):
            self.config.Write(key="ProgramLocation", value=progLoc)
        if not self.config.HasEntry("ConfigLocation"):
            self.config.Write(key="ConfigLocation", value=configLoc)
        if not self.config.HasEntry("ApplicationVersion"):
            self.config.Write(key="ApplicationVersion", value=appVersion)
        if not self.config.HasEntry("ApplicationName"):
            self.config.Write(key="ApplicationName", value="PyArchiver")
        if not self.config.HasEntry("VendorName"):
            self.config.Write(key="VendorName", value="Pascal | JCharles")
        if not self.config.HasEntry("Language"):
            self.config.Write(key="Language", value="fr")


    def SetLang(self, lang):
        if getTextType == "wx":
            self.SetLangWX(lang)
        elif getTextType == "py":
            self.SetLangPY(lang)

            
    def SetLangPY(self, lang):
        if lang in ["fr"]:
            langFr = gettext.translation("myapp", localeDir, languages=["fr"])
            langFr.install()

        if platform.system() == "Linux":
            try:
                # To get some language settings to display properly
                os.environ["LANGUAGE"] = "fr"

            except (ValueError, KeyError):
                pass


        else:
            langEn = gettext.translation("myapp", localeDir, languages=["en"])
            langEn.install()
        
        if platform.system() == "Linux":
            try:
                # To get some language settings to display properly
                os.environ["LANGUAGE"] = "en"

            except (ValueError, KeyError):
                pass
            
        
    def SetLangWX(self, lang):
        if lang in ["fr"]:
            if hasattr(self, "locale"):
                del self.locale
            self.locale = wx.Locale(wx.LANGUAGE_FRENCH, 
                        wx.LOCALE_LOAD_DEFAULT|wx.LOCALE_CONV_ENCODING)
            self.locale.AddCatalog("myapp")
            self.config.Write(key="Language", value="fr")

            if platform.system() == "Linux":
                os.environ["LANGUAGE"] = "fr"

                
        else:
            if hasattr(self, "locale"):
                del self.locale
            self.locale = wx.Locale(wx.LANGUAGE_ENGLISH, 
                        wx.LOCALE_LOAD_DEFAULT|wx.LOCALE_CONV_ENCODING)
            self.locale.AddCatalog("myapp")
            self.config.Write(key="Language", value="en")

            if platform.system() == "Linux":
                os.environ["LANGUAGE"] = "en"
                
#---------------------------------------------------------------------------

def main():
    app = My_App(False)
    app.MainLoop()

#---------------------------------------------------------------------------

if __name__ == "__main__" :
    main()



